
package com.gustozzi.distribucion.dao.util;

import java.sql.Connection;
import java.sql.SQLException;

import javax.naming.InitialContext;
import javax.sql.DataSource;

public class DataAccess
{

    private Connection con = null;

    private static String defaultDataSource = null;
    private String dataSource = "";

    public DataAccess()
    {
        dataSource = defaultDataSource;
    }

    public DataAccess(String dataSource)
    {
        this.dataSource = dataSource;
    }

    public static void setDefaultDataSource(String dataSource)
    {
        defaultDataSource = dataSource;
    }

    public Connection getConnection() throws DataAccessExceptions
    {
        if (con == null)
        {
            if (dataSource == null)
                throw new DataAccessExceptions("Data source no definido");
            try
            {
                InitialContext jndiContext = new InitialContext();
                DataSource ds = (DataSource) jndiContext.lookup(dataSource);
                con = ds.getConnection();
                con.setAutoCommit(false);

            }
            catch (Exception e1)
            {
                throw new DataAccessExceptions(e1);
            }
        }
        return con;
    }

    public void commit() throws DataAccessExceptions
    {
        try
        {
            if (con != null)
                con.commit();
        }
        catch (SQLException e)
        {
            throw new DataAccessExceptions(e);
        }

    }

    public void rollback() throws DataAccessExceptions
    {
        try
        {
            if (con != null)
                con.rollback();
        }
        catch (SQLException ignored)
        {
            throw new DataAccessExceptions(ignored);
        }
    }

    public void close() throws DataAccessExceptions
    {
        try
        {
            if (con != null)
            {
                con.close();
                con = null;
            }
        }
        catch (SQLException ignored)
        {
            throw new DataAccessExceptions(ignored);
        }
    }
}